package com.nuanshui.heatedloan.middleware.convert.annotation;

import com.nuanshui.heatedloan.middleware.convert.Converter;
import com.nuanshui.heatedloan.middleware.convert.ConverterService;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.HashMap;
import java.util.Map;

public class ConverterAnnotationBeanPostProcessor implements BeanPostProcessor,BeanFactoryAware,SmartInitializingSingleton{

	private Map<Integer,Converter> mapConverter=new HashMap<Integer,Converter>();

	private ConverterService converterService;

	public ConverterService getConverterService() {
		return converterService;
	}

	public void setConverterService(ConverterService converterService) {
		this.converterService = converterService;
	}
	
	private BeanFactory beanFactory;

	public BeanFactory getBeanFactory() {
		return beanFactory;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		//获取对象的class
		Class<?> targetClass = AopUtils.getTargetClass(bean);

		ConverterServiceAttribute converterServiceAttribute =  AnnotationUtils.getAnnotation(targetClass, ConverterServiceAttribute.class);

		if(converterServiceAttribute!=null)
		{
			setConverterService((ConverterService) bean);
		}

		ConverterAttribute converterAttribute =  AnnotationUtils.getAnnotation(targetClass, ConverterAttribute.class);
		if(converterAttribute!=null)  {//只有加了此注解的才进行 相关处理

			Converter converter=(Converter)bean;
			mapConverter.put(converterAttribute.typeId(),converter);
		}
		return bean;
	}

	@Override
	public void afterSingletonsInstantiated() {

		if(converterService !=null && mapConverter.size()>0)
		{
			converterService.addConverter(mapConverter);
		}
	}
}
